package cn.tedu.buycradserver.service.impl;

import cn.tedu.buycradserver.ex.ServiceException;
import cn.tedu.buycradserver.mapper.SkuMapper;
import cn.tedu.buycradserver.mapper.SpuMapper;
import cn.tedu.buycradserver.pojo.dto.SkuAddNewDTO;
import cn.tedu.buycradserver.pojo.entity.Sku;
import cn.tedu.buycradserver.service.ISkuService;
import cn.tedu.buycradserver.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class SkuServiceImpl implements ISkuService {
    @Autowired
    SkuMapper skuMapper;
    @Autowired
    SpuMapper spuMapper;
    @Override
    public void addNew(SkuAddNewDTO skuAddNewDTO) {
        int rows = spuMapper.countById(skuAddNewDTO.getSpuId());
        //查看存不存在
        if (rows==0){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"该种类不存在");
        }
        Sku sku = new Sku();
        BeanUtils.copyProperties(skuAddNewDTO,sku);
        //查询是否有库存
        int i = skuMapper.selectQuantity(sku.getId());
        if (i==0){
            skuMapper.insert(sku);
        }else if (i>0){
            //修改库存
           Sku sku1 = new Sku();
           BeanUtils.copyProperties(skuAddNewDTO,sku1);
           sku1.setQuantity(sku1.getQuantity()+skuMapper.selectQuantity(skuAddNewDTO.getId()));
        }else{
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"出问题了");
        }
    }

    @Override
    public void deleteById(Long id) {
        Sku sku = skuMapper.getSkuById(id);
        if (sku==null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"删除失败该商铺不存在");
        }
        int i = skuMapper.deleteById(id);
        if (i!=1){
            throw new ServiceException(ServiceCode.ERR_DELETE,"删除sku失败,服务器忙");
        }
    }
}
